/*
 * @Description: 新的朋友
 * @Author: fhw
 * @Date: 2023-01-14 22:43:25
 */
import { ArrowLeftOutlined } from '@ant-design/icons-vue'
import { isTrue } from '@/utils/tools'
import { computed, defineComponent, inject, onMounted, ref } from 'vue'
import './style.scss'
import { clone, equals } from 'ramda'
import { BasicDataModule, FriendsVerifyList } from '@/store/modules/basicData'
import { Friends, User } from '@/interface'
import { MenuItem } from '@/components/user/interface'
import UserInfo from '@/components/user/userInfo'
import { onSendMessage } from '../util'
import UserStrange from '@/components/user/strange'
import { ContextmenuItem } from '@/components/Contextmenu/interface'
import { successTips, errorTips } from '@/utils'
import { Socket } from 'socket.io-client'
import UserImg from '@/components/user/userImg'
import { useRouter } from 'vue-router'
enum ListAndInfoType {
	list = 'LIST',
	info = 'INFO',
}
interface PageState {
	type: ListAndInfoType
	userInfo?: User
	menu: MenuItem[]
	loading: boolean
	status: number | null
}
interface ApplyForVerificationParams {
	status: number
	friendsId: number
	id: number
}
export default defineComponent({
	setup() {
		const router = useRouter()
		const userId = localStorage.getItem('userId') as string
		// 通讯
		const socket = inject('socket') as Socket
		// 好友备注集合
		const friendsRemarksMap = computed<Map<string, string>>(() => {
			return BasicDataModule.friendsRemarksMap
		})
		// 设置好友验证消息已读
		if (isTrue(Object.keys(BasicDataModule.friendsMessage))) {
			socket.emit('setFriendsUnreadRecord', { ids: Object.keys(BasicDataModule.friendsMessage), userId })
		}
		onMounted(() => {
			if (!isTrue(BasicDataModule.friendsVerifyList)) {
				BasicDataModule.getFriendsVerifyList()
			}
			if (!isTrue(BasicDataModule.friendsMessage)) {
				socket.emit('getFriendsNotice', { userId })
			}
		})
		const pageState = ref<PageState>({
			type: ListAndInfoType.list,
			userInfo: {} as Friends,
			loading: false,
			status: null,
			menu: [
				{
					text: '发消息',
					handler: hanleSendMessage,
				},
			],
		})
		// 发消息并添加聊天历史记录
		async function hanleSendMessage() {
			const success = await onSendMessage(String(pageState.value.userInfo?.id))
			if (success) {
				toChat()
			}
		}
		function toChat() {
			router.push({
				path: '/index',
				query: {
					userId: pageState.value.userInfo?.id,
				},
			})
		}
		/** 好友验证记录 */
		const friendsVerify = computed(() => {
			return BasicDataModule.friendsVerifyList
		})
		function toUserInfo(user: Friends) {
			pageState.value.type = ListAndInfoType.info
			pageState.value.userInfo = clone(user.friends)
			if (pageState.value.userInfo) {
				pageState.value.userInfo.source = user.source as number
				pageState.value.status = user.status as number
			}
		}
		const contextmenu = (): ContextmenuItem[] => {
			return [
				{
					text: '删除',
					handler: deleteFriendsVerification,
				},
			]
		}
		async function deleteFriendsVerification(e: { getAttribute: (arg0: string) => any }) {
			const index = e.getAttribute('data-index')
			const friends = friendsVerify.value[index]
			friendsVerify.value[index].spinning = true
			const { success, msg } = await API.blog.chatUserFriends.deleteFriendsVerification.request({
				userId,
				friendsId: friends.friendsId,
			})
			friendsVerify.value[index].spinning = false
			if (success) {
				friendsVerify.value.splice(index, 1)
			} else {
				errorTips(msg)
			}
		}
		/**
		 * 验证好友申请
		 */
		async function applyForVerification({ status, friendsId, id }: ApplyForVerificationParams) {
			const params: API.blog.chatUserFriends.applyForVerification.Params = {
				friendsId,
				status,
				userId,
				id,
			}
			const { success, msg } = await API.blog.chatUserFriends.applyForVerification.request(params)
			success ? successTips(msg) : errorTips(msg)
			if (success) {
				BasicDataModule.getContacts()
				const index = friendsVerify.value.findIndex((item) => item.id === id)
				friendsVerify.value[index].status = status
			}
		}
		// 监听好友通过
		socket.on('applyForVerification', (data: ApplyForVerificationParams) => {
			const index = friendsVerify.value.findIndex((item) => item.id === data.id)
			friendsVerify.value[index].status = data?.status
			BasicDataModule.getContacts()
		})
		function friendsBtnRender(dataSource: FriendsVerifyList) {
			switch (dataSource.status) {
				case 0:
					return (
						<a-button
							type="primary"
							onClick={(e: { stopPropagation: () => void }) => {
								e.stopPropagation()
								applyForVerification({
									id: dataSource.id,
									friendsId: dataSource.friendsId,
									status: 1,
								})
							}}
						>
							接受
						</a-button>
					)
				case 1:
					return <span>已通过</span>
				case 2:
					return <span>待验证</span>
				default:
					return <span></span>
			}
		}
		return () => (
			<div id="newFriends">
				<header>
					{equals(pageState.value.type, ListAndInfoType.list) ? (
						'新的朋友'
					) : (
						<ArrowLeftOutlined
							style=" cursor: pointer;"
							onClick={() => {
								pageState.value.type = ListAndInfoType.list
								pageState.value.userInfo = {} as Friends
							}}
						/>
					)}
				</header>
				<div class="newFriends-main">
					{equals(pageState.value.type, ListAndInfoType.list) ? (
						<ul>
							{friendsVerify.value.map((item, index) => (
								<li onClick={() => toUserInfo(item as Friends)} data-index={index} v-contextmenu={contextmenu}>
									<a-spin spinning={item.spinning} wrapperClassName="newFriends-spin">
										<div class="headimgurl">
											<UserImg iconSize={60} imgSize={60} headimgurl={item.friends?.headimgurl} />
										</div>
										<div class="newFriends-userInfo">
											<div class="name one-hidden">
												{friendsRemarksMap.value.get(String(item.friends?.id)) ?? item.friends?.username}
											</div>
											<div class="verification">{item.verification}</div>
										</div>
										<div class="newFriends-btn">{friendsBtnRender(item)}</div>
									</a-spin>
								</li>
							))}
						</ul>
					) : (
						<div class="newFriends-user">
							{equals(pageState.value?.status as number, 1) && (
								<UserInfo
									v-model={[pageState.value.loading, 'loading']}
									dataSource={pageState.value.userInfo as User}
									menu={pageState.value.menu}
								/>
							)}
							{[0, 2].includes(pageState.value?.status as number) && (
								<UserStrange dataSource={pageState.value.userInfo as User} />
							)}
						</div>
					)}
				</div>
			</div>
		)
	},
})
